import React, { useEffect } from 'react';
import * as echarts from 'echarts';
import './pie.css';

export default function Pie() {
  useEffect(() => {
    const chartDom = document.getElementById('pieChart');
    const myChart = echarts.init(chartDom);
    
    const option = {
      tooltip: {
        trigger: 'item'
      },
      legend: {
        orient: 'vertical',
        right: '10%',
        top: 'center',
        itemWidth: 10,
        itemHeight: 10,
        icon: 'circle',
        formatter: function(name) {
          const data = option.series[0].data;
          let total = 0;
          let targetValue;
          data.forEach(function(item) {
            total += item.value;
            if (item.name === name) {
              targetValue = item.value;
            }
          });
          const percentage = ((targetValue / total) * 100).toFixed(0);
          return `${name} ${percentage}%`;
        }
      },
      color: ['#3ed4a7', '#ffd666', '#ff9f7f'],
      series: [
        {
          type: 'pie',
          radius: ['50%', '70%'],
          center: ['30%', '50%'],
          avoidLabelOverlap: false,
          label: {
            show: false
          },
          labelLine: {
            show: false
          },
          data: [
            { value: 28, name: '家政护理' },
            { value: 55, name: '康复理疗' },
            { value: 17, name: '上门体检' }
          ]
        }
      ]
    };

    option && myChart.setOption(option);

    // 清理函数
    return () => {
      myChart.dispose();
    };
  }, []);

  return <div id="pieChart" className="pie-chart"></div>;
}
